package com.kingyun.gpsinspection.purificationservice.services.iam.innerservice.accessory.impl;

import com.alibaba.fastjson.JSONObject;
import com.kingyun.gpsinspection.purificationservice.common.utils.ArrayMaxAndMinUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.accessory.A2DataInfoMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.accessory.A2DataInfo;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.accessory.IamOrganizationVo;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.accessory.IamA2DataInfoService;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.accessory.IamOrganizationService;
import com.kingyun.gpsinspection.purificationservice.common.enums.OrganizationLevelEnum;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.Organization;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.OutOrganizationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @version V1.0
 * @Package com.cqhilink.iot.integratedapplicationmanagement.services.innerservice.accessory.impl
 * @Description: ${TODO}(10日产气产水实现)
 * @author: lutianbo
 * @date: 2017/5/3,0003
 */

public class IamA2DataInfoServiceImpl implements IamA2DataInfoService{

    @Autowired
    private A2DataInfoMapper a2DataInfoMapper;
    @Autowired
    private IamOrganizationService organizationService;
    @Autowired
    private OutOrganizationService outOrganizationService;

    @Override
    public JSONObject query10WaterAndGas(String orgId,String type) throws Exception{
        boolean flag = false;
        // 返回结果集
        JSONObject jsonObject =new JSONObject();
        // 开始时间
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)-10);
        String startTime = datechange(calendar.getTime(),"yyy-MM-dd");
        // 结束时间
        String  endTime = datechange(new Date(),"yyy-MM-dd");
        // 作业区
        List<IamOrganizationVo> organizationList = new ArrayList<>();
        // 场站/井 以此组织为父节点的数据
        List<IamOrganizationVo> orgList = new ArrayList<>();
        // 查询组织信息
        Organization organization = outOrganizationService.queryOrganization(orgId);
        // 查询作业区
        if(type == null || "first".equals(type)){
            organizationList = organizationService.getZyqByOrgId(orgId);
            flag = true;
        }
        String secondId = null;

        // 若为所属场站或者井口则查询场站/井口以及儿子节点
        if(organization.getOrgLevelId().equals(OrganizationLevelEnum.ORG_LEVEL_STATION.getCode()) ||
                organization.getOrgLevelId().equals(OrganizationLevelEnum.ORG_LEVEL_WELL.getCode())){
             secondId = orgId;
        // 场站/井 以此组织为父节点的数据
        // 以第一个作业区id去查询子节点
        }else{
            if(flag){
                if(organizationList != null && organizationList.size() > 0){
                    secondId = organizationList.get(0).getId();
                }
            }
        }
        // 若参数不为空则去查询场站信息
        if(StringUtils.isNotEmpty(secondId)){
            orgList = organizationService.getNextOrganizationListByOrgId(secondId);
        }
        Map<String,Object> queryMap = new HashMap<>();
        String queryId = "";

        if("second".equals(type) || "firstAll".equals(type)){
            queryId=orgId;
        }else{
            queryId = organizationList.size() > 0 ? organizationList.get(0).getId(): orgId;
        }
        // 封装查询参数
        queryMap.put("orgId",queryId);
        queryMap.put("startTime",startTime);
        queryMap.put("endTime",endTime);
        // 查询10日产气产水数据
        A2DataInfo tenData = a2DataInfoMapper.query10WaterAndGas(queryMap);
        // 数据封装
        retJson(organizationList,orgList,tenData,jsonObject);
        return jsonObject;
    }

    /**
     * 封装10日产气产水数据
     * @param organizationList 作业区
     * @param orgList   场站/井
     * @param tenData   产气产水数据
     * @param jsonObject 返回结果
     * @return
     */
    private JSONObject retJson(List<IamOrganizationVo> organizationList, List<IamOrganizationVo> orgList, A2DataInfo tenData,JSONObject jsonObject) {
        // 产气结果集
        Double gasArry[] = new Double[0];
        // 产气最大值
        Double gasMax = 0.00;
        // 产气最小值
        Double gasMin = 0.00;
        // 产水结果集
        Double waterArry[] = new Double[0];
        // 产水最大值
        Double waterMax = 0.00;
        // 产水最小值
        Double waterMin = 0.00;
        // 最值
        if(tenData != null){
            //  气
            if(tenData.getTemSumGas().length()>0){
                gasArry = ArrayMaxAndMinUtil.stringArryToDoubleArry(tenData.getTemSumGas().split(","));
                gasMax = ArrayMaxAndMinUtil.getMax(gasArry)*1.02;
                gasMin = ArrayMaxAndMinUtil.getMin(gasArry)*0.98;
            }
            // 水
            if(tenData.getTenSumWater().length() > 0){
                waterArry = ArrayMaxAndMinUtil.stringArryToDoubleArry(tenData.getTenSumWater().split(","));
                waterMax = ArrayMaxAndMinUtil.getMax(waterArry)*1.02 ;
                waterMin = ArrayMaxAndMinUtil.getMin(waterArry)*0.98;

            }
        }
        // 倍数
        // Double maxbeishu = gasMax/waterMax;
        // Double maxbeishu = waterMax/gasMax;
        // 格式化(保留两位小数)
        DecimalFormat df   = new DecimalFormat("######0.00");
        // 纵坐标结果集
        List<Object> tenList = new ArrayList<>();

        // 10日产水基本数据
        Map<String,Object> waterMap = new HashMap<>();
        waterMap.put("name","产气");
        waterMap.put("unit","万方");
        waterMap.put("max",df.format(gasMax));
        waterMap.put("min",df.format(gasMin));
        waterMap.put("type","line");
        waterMap.put("data",gasArry);

        // 10日产气基本数据
        Map<String,Object> gasMap = new HashMap<>();
        gasMap.put("name","产水");
        gasMap.put("unit","方");
        // gasMap.put("max",df.format(gasMax/maxbeishu));
        // gasMap.put("min",df.format(gasMin/maxbeishu));
        gasMap.put("max",df.format(waterMax));
        gasMap.put("min",df.format(waterMin));
        gasMap.put("type","bar");
        gasMap.put("data",waterArry);

        // 封装纵坐标数据
        tenList.add(waterMap);
        tenList.add(gasMap);

        // 横坐标（日期）
        jsonObject.put("x",tenData != null && tenData.getTenSumWater().length() > 0 ? tenData.getTenDates().split(","):null);
        // 纵坐标（数据）
        jsonObject.put("y",tenList);
        // 作业区
        jsonObject.put("operatingArea",organizationList);
        // 场站/井
        jsonObject.put("stations",orgList);
        return jsonObject;
    }

    /**
     * 日期格式化
     * @param date
     * @param pattern
     * @return
     */
    private String datechange(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String demo = sdf.format(date);
        return demo;
    }

}
